﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using BAL.EstRec;
using Nav3.PGrid;
using BAL.EstRec.FDVIndicador;
using BAL.EstRec.FDVTotalRecurso;
using Nav3.ModelCapRHQ;
using System.ComponentModel;
using BAL.EstRec.FDVTotal;
using BAL.EstRec.FDVUtil;
using BAL.EstRec.FDVGrid;
//using BAL.PublishSharepoint;
using BAL.EstRec.FDVUndoPublish;
using Prueba.ViewModel;
using DataMapper;
using Prueba.ViewModel.Converters;
using System.Collections.ObjectModel;
using Prueba.Model;
using System.Windows.Threading;
using Microsoft.Windows.Controls.Primitives;
using Prueba.ViewModel.Utils;

namespace Nav3
{
    /// <summary>
    /// Lógica de interacción para CapturaRHQ.xaml
    /// </summary>
    public partial class CapturaRHQ : UserControl, InterfazControl, ISave,IPublish
    {
        public bool IsModified { get; set; }
        private int posDescColumn;
        private long currentUnidVersion;
        private string currentPositionCode;
        private CapFdvPivot2Collection capPivot;
        private CapturasPFDV capsFdv;
        private ModelCapFdvIndicador m;
        private ModelCapFdvTotalRecurso mTotalRecurso;
        private ModelCapFdvTotales mTotalTotal;
        private List<PosInfoAttribute> l;
        private Nav3.PGrid.PGrid pg;
        private Nav3.PGrid.PGrid pgTotal;
        private Nav3.PGrid.PGrid pgTotalTotal;
        private FDVRecursoRule rule;

        private int posColumnWidht;
        //private FdvVersion currentFdvVersion;

        public CapturaRHQ()
        {
            InitializeComponent();
            this.currentPositionCode = "";
            this.currentUnidVersion = 0;
            //this.DataContext = new FdvGridViewModel(new FdvDataMapper(), -1,new HelperRePublishConfirm(),new HelperSaveDialog(),this.currentPositionCode);
            //this.currentFdvVersion = null;
            //this.rule = new FDVRecursoRule(3, 2);
        }////////////////

        //private void changeData(object pcSender, PropertyChangedEventArgs pcArgs)
        //{

        //    this.IsModified = true;
        //    //Obtener el objeto 

        //    RecursoIndexer capFdv2 = (from o in this.capPivot
        //                              where o.Pos.idPos == (pcSender as RecursoIndexer).Pos.idPos
        //                              select o).First();

        //    CapFDVIndicador cfi = this.m.Calculate(capFdv2);
        //    CapturaPivotFDV capFdv1 = (from o in this.capsFdv.ObCollPFDV
        //                               where o.pos.idPos == capFdv2.Pos.idPos
        //                                   && o.recurso.idRecurso == pcArgs.PropertyName
        //                               select o).First();

        //    capFdv1.cantidad = capFdv2[pcArgs.PropertyName];

        //    try
        //    {
        //        var resInd = (from o in this.m.entry
        //                      where o.Pos.idPos == capFdv2.Pos.idPos
        //                      select o).First();

        //        resInd.NumIniciativas = cfi.NumIniciativas;
        //        resInd.NumRecursos = cfi.NumRecursos;
        //        resInd.VisitasSugeridas = cfi.VisitasSugeridas;
        //        resInd.TiempoImplementacion = cfi.TiempoImplementacion;
        //    }
        //    catch (Exception ex)
        //    {
        //        return;
        //    }


        //    //Obtener total x recurso

        //    //Calcular total
        //    CapFDVTotalRecurso r = this.mTotalRecurso.calculate(pcArgs.PropertyName, this.capsFdv);

        //    var resEntry = from o in mTotalRecurso.entry
        //                   where o.Recurso.idRecurso == pcArgs.PropertyName
        //                   select o;
        //    foreach (var re in resEntry)
        //    {
        //        re.Iniciativas = r.Iniciativas;
        //        re.NumIniciativas = r.NumIniciativas;
        //        re.TiempoImplementacion = r.TiempoImplementacion;
        //        re.VisitasSugeridas = r.VisitasSugeridas;
        //        re.NumRecursos = r.NumRecursos;
        //        re.IsMaxCantRecursoRuleExceded = r.IsMaxCantRecursoRuleExceded;
        //        re.MaxCantidadRecursoPermitido = r.MaxCantidadRecursoPermitido;
        //    }

        //    //Cacular totales
        //    CapFDVTotalRecurso rTotalTotal = this.mTotalTotal.calculateTotal(this.m);
        //    foreach (CapFDVTotalRecurso tmp in mTotalTotal.entry)
        //    {
        //        switch (tmp.Recurso.idRecurso)
        //        {
        //            case "timpTotal":
        //                tmp.TiempoImplementacion = rTotalTotal.TiempoImplementacion;
        //                break;
        //            case "visitasTotal":
        //                tmp.VisitasSugeridas = rTotalTotal.VisitasSugeridas;
        //                break;
        //            //case "numRecursos":
        //            //    tmp.NumRecursos = rTotalTotal.NumRecursos;
        //            //    break;
        //            //case "numIniciativas":
        //            //    tmp.NumIniciativas = rTotalTotal.NumIniciativas;
        //            //    break;    
        //        }
        //    }
        //}

        //private void createModelObjects()
        //{
        //    //Obtener la info de la base de datos de la version para llenar la coleccion
        //    List<CapturaPivotFDV> cpf = CapturaPivotFDV.GetCapturaPivotFDV(this.currentUnidVersion, this.currentPositionCode);
        //    capsFdv = new CapturasPFDV(new CollectionsPivotFDV(cpf));

        //    //
        //    List<Recurso> recursos = Recurso.GetRecursosListSortedIniciativa();
        //    this.capPivot = CapturaFdv.GetPivotCapturaFDV(this.currentFdvVersion.UnidFdvBgtVersion, this.rule, recursos);

        //    foreach (RecursoIndexer p in this.capPivot)
        //    {
        //        p.PropertyChanged += changeData;
        //    }

        //    //Setear evento para el calculo de los totales
        //    #region comentado
        //    // .PropertyChanged += delegate(object pcSender, PropertyChangedEventArgs pcArgs)
        //    //{
        //    //    this.IsModified = true;
        //    //    //Calcular Indicadores
        //    //    CapFDVIndicador cfi = this.m.Calculate(((CapturaPivotFDV)pcSender).pos.idPos, this.capsFdv);
        //    //    resInd.NumIniciativas = cfi.NumIniciativas;
        //    //    resInd.NumRecursos = cfi.NumRecursos;
        //    //    resInd.VisitasSugeridas = cfi.VisitasSugeridas;
        //    //    resInd.TiempoImplementacion = cfi.TiempoImplementacion;

        //    //    //Obtener total x recurso

        //    //    //Calcular total
        //    //    CapFDVTotalRecurso r = this.mTotalRecurso.calculate(((CapturaPivotFDV)pcSender).recurso.idRecurso, this.capsFdv);

        //    //    var resEntry = from o in mTotalRecurso.entry
        //    //                   where o.Recurso.idRecurso == args.row
        //    //                   select o;
        //    //    foreach (var re in resEntry)
        //    //    {
        //    //        re.Iniciativas = r.Iniciativas;
        //    //        re.NumIniciativas = r.NumIniciativas;
        //    //        re.TiempoImplementacion = r.TiempoImplementacion;
        //    //        re.VisitasSugeridas = r.VisitasSugeridas;
        //    //        re.NumRecursos = r.NumRecursos;
        //    //    }

        //    //    //Cacular totales
        //    //    CapFDVTotalRecurso rTotalTotal = this.mTotalTotal.calculateTotal(this.m);
        //    //    foreach (CapFDVTotalRecurso tmp in mTotalTotal.entry)
        //    //    {
        //    //        switch (tmp.Recurso.idRecurso)
        //    //        {
        //    //            case "timpTotal":
        //    //                tmp.TiempoImplementacion = rTotalTotal.TiempoImplementacion;
        //    //                break;
        //    //            case "visitasTotal":
        //    //                tmp.VisitasSugeridas = rTotalTotal.VisitasSugeridas;
        //    //                break;
        //    //            //case "numRecursos":
        //    //            //    tmp.NumRecursos = rTotalTotal.NumRecursos;
        //    //            //    break;
        //    //            //case "numIniciativas":
        //    //            //    tmp.NumIniciativas = rTotalTotal.NumIniciativas;
        //    //            //    break;    
        //    //        }
        //    //    }

        //    //};
        //    #endregion

        //    //Crear objeto model
        //    FDVRecursoRule rule = FDVRecursoRule.GetRule();
        //    m = new ModelCapFdvIndicador(this.capPivot, new FDVRecursoRule(3, 2), Recurso.GetRecursosList());

        //    //
        //    mTotalRecurso = new ModelCapFdvTotalRecurso(capsFdv);
        //    //mTotalRecurso = new ModelCapFdvTotalRecurso(capsFdv, m); //20121206

        //    //
        //    this.mTotalTotal = new ModelCapFdvTotales(this.m);



        //    //
        //    l = new List<PosInfoAttribute>();
        //    l.Add(new PosInfoAttribute(false, "Nombre Cliente", 9));//1
        //    l.Add(new PosInfoAttribute(false, "Razón Social", 8)); //0
        //    l.Add(new PosInfoAttribute(false, "Potencial", 2));
        //    l.Add(new PosInfoAttribute(false, "Estado", 3));
        //    l.Add(new PosInfoAttribute(false, "Municipio", 4));
        //    l.Add(new PosInfoAttribute(false, "Localidad", 5));
        //    l.Add(new PosInfoAttribute(false, "Colonia", 6));
        //    l.Add(new PosInfoAttribute(false, "Código Postal", 7));
        //    l.Add(new PosInfoAttribute(false, "SubCanal", 1));//8
        //    l.Add(new PosInfoAttribute(false, "Canal", 0));//9
        //    /*
        //    l = new List<PosInfoAttribute>();
        //    l.Add(new PosInfoAttribute(false, "Nombre Cliente", 1));
        //    l.Add(new PosInfoAttribute(false, "Razón Social", 0));
        //    //l.Add(new PosInfoAttribute(false, "Código Postal", 7));
        //    //l.Add(new PosInfoAttribute(false, "Colonia", 6));
        //    //l.Add(new PosInfoAttribute(false, "Localidad", 5));
        //    //l.Add(new PosInfoAttribute(false, "Municipio", 4));
        //    //l.Add(new PosInfoAttribute(false, "Estado", 3));
        //    //l.Add(new PosInfoAttribute(false, "Potencial", 2));
        //    //l.Add(new PosInfoAttribute(false, "SubCanal", 1));
        //    //l.Add(new PosInfoAttribute(false, "Canal", 0));
        //     * */
        //}

        //private void createDataGrid()
        //{
        //    //Obtener listado de llaves del primer elemento de capPivot
        //    string[] keys = this.capPivot[0].getKeys();

        //    ////Agregar columna de pos
        //    //Binding posBinding = new Binding("Pos.idPos");
        //    //posBinding.Mode = BindingMode.TwoWay;

        //    //this.dataGridRightData.Columns.Add(
        //    //    new DataGridTextColumn()
        //    //    {
        //    //        Header = "Pos",
        //    //        Binding = posBinding,
        //    //        Width = 110
        //    //    }
        //    //);


        //    //mTotalRecurso
        //    //Ligar datos al dataGrid
        //    this.dataGridRightData.ItemsSource = this.capPivot;

        //    //Hacer ciclo por las keys para enlazar a las columnas del grid
        //    foreach (string key in keys)
        //    {
        //        //this.capPivot[0].RecursoIndexer
        //        Binding bgkColor = new Binding("[" + key + "]");
        //        bgkColor.Mode = BindingMode.TwoWay;
        //        bgkColor.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;

        //        //************* para pintado de columna si excede regla de max recurso
        //        var resx = (from o in mTotalRecurso.entry
        //                    where o.Recurso.idRecurso == key
        //                    select o).First();


        //        Style s = new Style();

        //        //Crear binding para background de color
        //        Binding bgColColor = new Binding("IsMaxCantRecursoRuleExceded");
        //        bgColColor.Source = (CapFDVTotalRecurso)resx;// x;
        //        bgColColor.Mode = BindingMode.TwoWay;
        //        bgColColor.Converter = new RuleExcededBgkColorConverter();
        //        bgkColor.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;

        //        s.TargetType = typeof(DataGridCell);

        //        s.Setters.Add(new Setter
        //        {
        //            Property = DataGridCell.BackgroundProperty,
        //            Value = bgColColor
        //        });
        //        s.Setters.Add(new Setter
        //        {
        //            Property = TextBlock.TextAlignmentProperty,
        //            Value = TextAlignment.Center
        //        });
        //        //-------------------- agregar trigger
        //        DataTrigger tg = new DataTrigger()
        //        {
        //            Binding = new Binding("IsSelected"),
        //            Value = true
        //        };

        //        s.Setters.Add(new Setter()
        //        {
        //            Property = DataGridCell.ForegroundProperty,
        //            Value = Brushes.Black
        //        });
        //        //s.Setters.Add(new Setter()
        //        //{
        //        //    Property = DataGridCell.BackgroundProperty,
        //        //    Value = Brushes.Salmon
        //        //});

        //        s.Triggers.Add(tg);

        //        //****************************************************************

        //        this.dataGridRightData.Columns.Add(
        //            new DataGridTextColumn()
        //            {
        //                Header = key,
        //                Binding = bgkColor,
        //                Width = 110,//170,//
        //                CellStyle = s    //
        //            }
        //        );
        //    }
        //}

        //private void createDataGridDataFDV()
        //{
        //    //Nav3.PGrid.PGrid 
        //    pg = new Nav3.PGrid.PGrid(this.leftHeader, this.leftData, this.rightHeader, this.rightData);
        //    #region comentado
        //    //pg.CellAdded += delegate(object sender, CellAddedEventArgs args)
        //    //{
        //    //    //Obtener Indicador
        //    //    var resInd = (from o in this.m.entry
        //    //                  where o.Pos.idPos == args.col
        //    //                  select o).First();

        //    //    //Obtener resx
        //    //    var resx = (from o in capsFdv.ObCollPFDV
        //    //               where o.pos.idPos == args.col && o.recurso.idRecurso == args.row
        //    //               select o).First();

        //    //    //Setear evento para el calculo de los totales
        //    //    resx.PropertyChanged += delegate(object pcSender, PropertyChangedEventArgs pcArgs)
        //    //    {
        //    //        this.IsModified = true;
        //    //        //Calcular Indicadores
        //    //        CapFDVIndicador cfi= this.m.Calculate(((CapturaPivotFDV)pcSender).pos.idPos, this.capsFdv);
        //    //        resInd.NumIniciativas = cfi.NumIniciativas;
        //    //        resInd.NumRecursos = cfi.NumRecursos;
        //    //        resInd.VisitasSugeridas = cfi.VisitasSugeridas;
        //    //        resInd.TiempoImplementacion = cfi.TiempoImplementacion;

        //    //        //Obtener total x recurso

        //    //        //Calcular total
        //    //        CapFDVTotalRecurso r= this.mTotalRecurso.calculate(((CapturaPivotFDV)pcSender).recurso.idRecurso, this.capsFdv);

        //    //        var resEntry = from o in mTotalRecurso.entry
        //    //                       where o.Recurso.idRecurso == args.row
        //    //                       select o;
        //    //        foreach (var re in resEntry)
        //    //        {
        //    //            re.Iniciativas = r.Iniciativas;
        //    //            re.NumIniciativas = r.NumIniciativas;
        //    //            re.TiempoImplementacion = r.TiempoImplementacion;
        //    //            re.VisitasSugeridas = r.VisitasSugeridas;
        //    //            re.NumRecursos = r.NumRecursos;
        //    //        }

        //    //        //Cacular totales
        //    //        CapFDVTotalRecurso rTotalTotal = this.mTotalTotal.calculateTotal(this.m);
        //    //        foreach (CapFDVTotalRecurso tmp in mTotalTotal.entry)
        //    //        {
        //    //            switch (tmp.Recurso.idRecurso)
        //    //            {
        //    //                case "timpTotal":
        //    //                    tmp.TiempoImplementacion = rTotalTotal.TiempoImplementacion;
        //    //                    break;
        //    //                case "visitasTotal":
        //    //                    tmp.VisitasSugeridas = rTotalTotal.VisitasSugeridas;
        //    //                    break;
        //    //                //case "numRecursos":
        //    //                //    tmp.NumRecursos = rTotalTotal.NumRecursos;
        //    //                //    break;
        //    //                //case "numIniciativas":
        //    //                //    tmp.NumIniciativas = rTotalTotal.NumIniciativas;
        //    //                //    break;    
        //    //            }
        //    //        }

        //    //    };


        //    //    Binding bind = new Binding("cantidad");
        //    //    bind.Source = (CapturaPivotFDV)resx;   //(CapturaFdv)x;    //
        //    //    bind.Mode = BindingMode.TwoWay;
        //    //    ((TextBlock)((StackPanel)((Border)args.tb).Child).Children[0]).SetBinding(TextBlock.TextProperty, bind);

        //    //    Binding bind2 = new Binding("cantidad");
        //    //    bind2.Source = (CapturaPivotFDV)resx;   //(CapturaFdv)x;    //
        //    //    bind2.Mode = BindingMode.TwoWay;
        //    //    bind2.NotifyOnSourceUpdated = true;
        //    //    bind2.NotifyOnTargetUpdated = true;
        //    //    ((TextBox)((StackPanel)((Border)args.tb).Child).Children[1]).SetBinding(TextBox.TextProperty, bind2);

        //    //    //Crear binding para background de color
        //    //    Binding bgkColor = new Binding("IsRuleExceded");
        //    //    bgkColor.Source = resInd;
        //    //    bgkColor.Mode = BindingMode.TwoWay;
        //    //    bgkColor.Converter = new RuleExcededBgkColorConverter();
        //    //    ((Border)args.tb).SetBinding(Border.BackgroundProperty, bgkColor);
        //    //};
        //    //Obtener lista de recursos
        //    #endregion
        //    List<Recurso> recursosList = Recurso.GetRecursosListSortedIniciativa();

        //    pg.ColumnRowSubHeaderAdded += delegate(object columnRowSubHeaderSender, CellAddedEventArgs columnRowSubHeaderArgs)
        //    {
        //        var resFirst = (from o in capsFdv.ObCollPFDV
        //                        where o.recurso.idRecurso == columnRowSubHeaderArgs.row
        //                        select o.recurso).First();
        //        TextBlock t = ((TextBlock)((Border)columnRowSubHeaderArgs.tb).Child);
        //        t.ToolTip = resFirst.recurso;
        //        t.HorizontalAlignment = HorizontalAlignment.Center;
        //    };

        //    pg.ColumnRowHeaderAdded += delegate(object columnRowHeaderSender, CellAddedEventArgs columnRowHeaderArgs)
        //    {
        //        var resFirst = (from o in capsFdv.ObCollPFDV
        //                        where o.recurso.idIniciativa == columnRowHeaderArgs.row
        //                        select o.recurso).First();
        //        TextBlock t = ((TextBlock)((Border)columnRowHeaderArgs.tb).Child);
        //        ((Border)columnRowHeaderArgs.tb).Cursor = Cursors.Hand;
        //        ((Border)columnRowHeaderArgs.tb).IsHitTestVisible = true;
        //        t.ToolTip = resFirst.iniciativa;

        //        var guideLine = "";
        //        try
        //        {
        //            guideLine = (from o in recursosList
        //                         where o.idRecurso == resFirst.idRecurso
        //                         select o.guidelines).First();
        //        }
        //        catch (Exception ex)
        //        {
        //            ;
        //        }

        //        t.Cursor = Cursors.Hand;

        //        t.MouseUp += delegate(object tSender, MouseButtonEventArgs tEventArgs)
        //        {
        //            try
        //            {
        //                System.Diagnostics.Process.Start(guideLine);
        //            }
        //            catch (Exception ex)
        //            {
        //                MessageBox.Show("No se pudo acceder a la página : " + @resFirst.guidelines + "\nDetalles : " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
        //            }

        //        };
        //        t.HorizontalAlignment = HorizontalAlignment.Center;
        //    };



        //    string idIniciativaAnt = recursosList[0].idIniciativa;

        //    List<string> recursosHeader = new List<string>();
        //    foreach (var r in recursosList)
        //    {
        //        if (r.idIniciativa != idIniciativaAnt)
        //        {
        //            pg.addRowHeaderData((new RowHeaders(idIniciativaAnt, recursosHeader)) as IPGridRowHeader);
        //            idIniciativaAnt = r.idIniciativa;
        //            recursosHeader = new List<string>();
        //        }
        //        recursosHeader.Add(r.idRecurso);
        //    }
        //    pg.addRowHeaderData((new RowHeaders(idIniciativaAnt, recursosHeader)) as IPGridRowHeader);


        //    //Obtener lista ordenada de pos
        //    List<Pos> posColl = Pos.GetPosList();

        //    //Obtener Canal que se mostraran como columna congelada
        //    var resCanal = (from o in posColl
        //                    orderby o.idPos
        //                    select
        //                     o).Distinct().Select(m => m.Canal).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("Canal", resCanal, false, 130);

        //    //Obtener SubCanal que se mostraran como columna congelada
        //    var resSubCanal = (from o in posColl
        //                       orderby o.idPos
        //                       select
        //                        o).Distinct().Select(m => m.SubCanal).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("SubCanal", resSubCanal, false, 100);


        //    //Obtener Municipio que se mostraran como columna congelada
        //    var resPotencial = (from o in posColl
        //                        orderby o.idPos
        //                        select
        //                         o).Distinct().Select(m => m.Potencial).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("Potencial", resPotencial, false, 180);

        //    //Obtener EStado que se mostraran como columna congelada
        //    var resEstado = (from o in posColl
        //                     orderby o.idPos
        //                     select
        //                      o).Distinct().Select(m => m.Estado).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("Estado", resEstado, false, 150);

        //    //Obtener Municipio que se mostraran como columna congelada
        //    var resMunicipio = (from o in posColl
        //                        orderby o.idPos
        //                        select
        //                         o).Distinct().Select(m => m.Municipio).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("Municipio", resMunicipio, false, 180);

        //    //Obtener Localidad que se mostraran como columna congelada
        //    var resLocalidad = (from o in posColl
        //                        orderby o.idPos
        //                        select
        //                         o).Distinct().Select(m => m.Localidad).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("Localidad", resLocalidad, false, 230);



        //    //Obtener Canal que se mostraran como columna congelada
        //    var resColonia = (from o in posColl
        //                      orderby o.idPos
        //                      select
        //                       o).Distinct().Select(m => m.Colonia).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("Colonia", resColonia, false, 250);

        //    //Obtener Canal que se mostraran como columna congelada
        //    var resCodigoPostal = (from o in posColl
        //                           orderby o.idPos
        //                           select
        //                            o).Distinct().Select(m => m.codigoPostal).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("Código Postal", resCodigoPostal, false, 250);

        //    //Obtener RazonSocial que se mostraran como columna congelada
        //    var resRazonSocial = (from o in capsFdv.ObCollPFDV
        //                          orderby o.pos.idPos
        //                          select
        //                           o.pos).Distinct().Select(m => m.razonSocial).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("Razón Social", resRazonSocial, false, 250);

        //    //Obtener Nombre POs que se mostraran como columna congelada
        //    var resNombrePos = (from o in capsFdv.ObCollPFDV
        //                        orderby o.pos.idPos
        //                        select
        //                         o.pos).Distinct().Select(m => m.pos).ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("Nombre", resNombrePos, false, 250);

        //    //Obtener los POS que se mostraran como columna congelada
        //    var res2 = (from o in capsFdv.ObCollPFDV
        //                orderby o.pos.idPos
        //                select
        //                 o.pos.idPos).Distinct().ToList();//.Distinct(new RecursoComparer()).ToList() ;
        //    pg.addColumnFrezze("POS", res2, true);

        //    pg.generateRowHeader();
        //    pg.generateFreezeCols();
        //    //pg.generateRowData();

        //    this.setBlueHeaderStyle(pg);
        //    this.setGrayFreezeColStyle(pg);
        //}

        //private void CreateDataGridIndicadores()
        //{
        //    //Crear el grid
        //    Nav3.PGrid.PGrid pgInd = new Nav3.PGrid.PGrid(this.leftHeaderKpi, this.leftDataKpi, this.rightHeaderKpi, this.rightDataKpi);
        //    pgInd.colFreezeWith = 90;
        //    pgInd.colWidth = 90;
        //    pgInd.IsEditEnable = false;

        //    pgInd.CellAdded += delegate(object sender, CellAddedEventArgs args)
        //    {
        //        var resx = (from o in m.entry
        //                    where o.Pos.idPos == args.col
        //                    select o).Take(1);

        //        foreach (var x in resx)
        //        {
        //            string indicador = "";

        //            switch (args.row)
        //            {
        //                case "Tiempo Imp.":
        //                    indicador = "TiempoImplementacion";
        //                    break;
        //                case "V. Sugeridas":
        //                    indicador = "VisitasSugeridas";
        //                    break;
        //                case "Iniciativas":
        //                    indicador = "NumIniciativas";
        //                    break;
        //                case "Recursos":
        //                    indicador = "NumRecursos";
        //                    break;
        //            }

        //            Binding bind = new Binding(indicador);
        //            bind.Source = (CapFDVIndicador)x;   //(CapturaFdv)x;    //
        //            bind.Mode = BindingMode.TwoWay;
        //            TextBlock t = ((TextBlock)((Border)args.tb).Child);
        //            t.HorizontalAlignment = HorizontalAlignment.Center;
        //            t.SetBinding(TextBlock.TextProperty, bind);
        //            t.SetBinding(TextBox.TextProperty, bind);

        //            //Obtener
        //            var resInd = (from o in this.m.entry
        //                          where o.Pos.idPos == args.col
        //                          select o).First();

        //            //Crear binding para background de color
        //            Binding bgkColor = new Binding("IsRuleExceded");
        //            bgkColor.Source = resInd;
        //            bgkColor.Mode = BindingMode.TwoWay;
        //            bgkColor.Converter = new RuleExcededBgkColorConverter();
        //            ((Border)args.tb).SetBinding(Border.BackgroundProperty, bgkColor);
        //        }
        //    };

        //    //Setear rowheaders
        //    pgInd.colWidth = 80;
        //    pgInd.colFreezeWith = 80;
        //    pgInd.addRowHeaderData((new RowHeaders("Indicadores", new List<string>() { "Tiempo Imp.", "V. Sugeridas", "Iniciativas", "Recursos" })) as IPGridRowHeader);

        //    //Setear Freeze columns
        //    var res2 = (from o in capsFdv.ObCollPFDV
        //                orderby o.pos.idPos
        //                select
        //                 o.pos.idPos).Distinct().ToList();//.Distinct(new RecursoComparer()).ToList() ;

        //    //Generar List
        //    pgInd.addColumnFrezze("POS", res2, true);
        //    pgInd.generateRowHeader();
        //    pgInd.generateFreezeCols();
        //    pgInd.generateRowData();

        //    this.setBlueHeaderStyle(pgInd);
        //}

        //private void CreateDataGridTotales()
        //{
        //    pgTotal = new Nav3.PGrid.PGrid(this.leftHeaderTotal, this.leftDataTotal, this.rightHeaderTotal, this.rightDataTotal);
        //    pgTotal.IsEditEnable = false;
        //    //-------- 2012-12-11
        //    pgTotal.colFreezeWith = 170;
        //    pgTotal.colWidth = 110;
        //    //--------

        //    pgTotal.CellAdded += delegate(object sender, CellAddedEventArgs args)
        //    {
        //        var resx = (from o in mTotalRecurso.entry
        //                    where o.Recurso.idRecurso == args.row
        //                    select o).Take(1);

        //        foreach (var x in resx)
        //        {
        //            string indicador = "";

        //            switch (args.col)
        //            {
        //                case "Tiempo Implementacion":
        //                    indicador = "TiempoImplementacion";
        //                    break;
        //                case "Visitas Sugeridas":
        //                    indicador = "VisitasSugeridas";
        //                    break;
        //                case "Recursos":
        //                    indicador = "NumRecursos";
        //                    break;
        //                case "Disponible":
        //                    indicador = "MaxCantidadRecursoPermitido";
        //                    break;
        //            }

        //            Binding bind = new Binding(indicador);
        //            bind.Source = (CapFDVTotalRecurso)x;   //(CapturaFdv)x;    //
        //            bind.Mode = BindingMode.TwoWay;
        //            TextBlock t = ((TextBlock)((Border)args.tb).Child);
        //            t.HorizontalAlignment = HorizontalAlignment.Center;
        //            t.SetBinding(TextBlock.TextProperty, bind);
        //            t.SetBinding(TextBox.TextProperty, bind);

        //            if (indicador == "NumRecursos")
        //            {
        //                //Crear binding para background de color
        //                Binding bgkColor = new Binding("IsMaxCantRecursoRuleExceded");
        //                bgkColor.Source = x;
        //                bgkColor.Mode = BindingMode.TwoWay;
        //                bgkColor.Converter = new RuleExcededBgkColorConverter();
        //                ((Border)args.tb).SetBinding(Border.BackgroundProperty, bgkColor);
        //            }
        //        }
        //    };

        //    //Setear RowHeaders
        //    //Obtener lista de recursos
        //    List<Recurso> recursosList = Recurso.GetRecursosListSortedIniciativa();
        //    string idIniciativaAnt = recursosList[0].idIniciativa;
        //    List<string> recursosHeader = new List<string>();
        //    foreach (var r in recursosList)
        //    {
        //        if (r.idIniciativa != idIniciativaAnt)
        //        {
        //            pgTotal.addRowHeaderData((new RowHeaders(idIniciativaAnt, recursosHeader)) as IPGridRowHeader);
        //            idIniciativaAnt = r.idIniciativa;
        //            recursosHeader = new List<string>();
        //        }
        //        recursosHeader.Add(r.idRecurso);
        //    }
        //    pgTotal.addRowHeaderData((new RowHeaders(idIniciativaAnt, recursosHeader)) as IPGridRowHeader);

        //    //CrearFreeze cols
        //    //pgTotal.addColumnFrezze("Labels", new List<string>() { "Tiempo Implementacion", "Visitas Sugeridas", "Recursos" }, true);
        //    pgTotal.addColumnFrezze("Labels", new List<string>() { "Tiempo Implementacion", "Visitas Sugeridas", "Recursos", "Disponible" }, true);   //20121207
        //    pgTotal.generateRowHeader();
        //    pgTotal.generateFreezeCols();
        //    pgTotal.generateRowData();

        //    this.setGrayFreezeColStyle(pgTotal);
        //}

        //private void CreateDataGridTotalesTotales()
        //{
        //    pgTotalTotal = new Nav3.PGrid.PGrid(this.leftHeaderTotalTotal, this.leftDataTotalTotal, this.rightHeaderTotalTotal, this.rightDataTotalTotal);
        //    pgTotalTotal.colFreezeWith = 80;
        //    pgTotalTotal.colWidth = 80;
        //    pgTotalTotal.IsEditEnable = false;

        //    pgTotalTotal.CellAdded += delegate(object sender, CellAddedEventArgs args)
        //    {

        //        if (String.Compare(args.col, "Tiempo Implementacion") == 0 && String.Compare(args.row, "Tiempo Implementacion") == 0)
        //        {
        //            //Agregar total de tiempo de implementacion
        //            var timpTotal = (from o in this.mTotalTotal.entry
        //                             where o.Recurso.idRecurso == "timpTotal"
        //                             select o).First();
        //            Binding bind = new Binding("TiempoImplementacion");
        //            bind.Source = (CapFDVTotalRecurso)timpTotal;   //(CapturaFdv)x;    //
        //            bind.Mode = BindingMode.TwoWay;
        //            TextBlock t = ((TextBlock)((Border)args.tb).Child);
        //            t.HorizontalAlignment = HorizontalAlignment.Center;
        //            t.SetBinding(TextBlock.TextProperty, bind);
        //            t.SetBinding(TextBox.TextProperty, bind);
        //        }
        //        if (String.Compare(args.col, "Visitas Sugeridas") == 0 && String.Compare(args.row, "Visitas Sugeridas") == 0)
        //        {
        //            //Agregar total de tiempo de implementacion
        //            var visitasTotal = (from o in this.mTotalTotal.entry
        //                                where o.Recurso.idRecurso == "visitasTotal"
        //                                select o).First();
        //            Binding bind = new Binding("VisitasSugeridas");
        //            bind.Source = (CapFDVTotalRecurso)visitasTotal;   //(CapturaFdv)x;    //
        //            bind.Mode = BindingMode.TwoWay;
        //            TextBlock t = ((TextBlock)((Border)args.tb).Child);
        //            t.HorizontalAlignment = HorizontalAlignment.Center;
        //            t.SetBinding(TextBlock.TextProperty, bind);
        //            t.SetBinding(TextBox.TextProperty, bind);
        //        }
        //        #region comentado
        //        //if (String.Compare(args.col, "Visitas Sugeridas") == 0 && String.Compare(args.row, "NumRecursos") == 0)
        //        //{
        //        //    //Agregar total de tiempo de implementacion
        //        //    var numRecursos = (from o in this.mTotalTotal.entry
        //        //                        where o.Recurso.idRecurso == "numRecursos"
        //        //                        select o).First();
        //        //    Binding bind = new Binding("NumRecursos");
        //        //    bind.Source = (CapFDVTotalRecurso)numRecursos;   //(CapturaFdv)x;    //
        //        //    bind.Mode = BindingMode.TwoWay;
        //        //    TextBlock t = ((TextBlock)((Border)args.tb).Child);
        //        //    t.HorizontalAlignment = HorizontalAlignment.Center;
        //        //    t.SetBinding(TextBlock.TextProperty, bind);
        //        //    t.SetBinding(TextBox.TextProperty, bind);
        //        //}
        //        //if (String.Compare(args.col, "Visitas Sugeridas") == 0 && String.Compare(args.row, "NumIniciativas") == 0)
        //        //{
        //        //    //Agregar total de tiempo de implementacion
        //        //    var numIniciativas = (from o in this.mTotalTotal.entry
        //        //                       where o.Recurso.idRecurso == "NumIniciativas"
        //        //                       select o).First();
        //        //    Binding bind = new Binding("NumIniciativas");
        //        //    bind.Source = (CapFDVTotalRecurso)numIniciativas;   //(CapturaFdv)x;    //
        //        //    bind.Mode = BindingMode.TwoWay;
        //        //    TextBlock t = ((TextBlock)((Border)args.tb).Child);
        //        //    t.HorizontalAlignment = HorizontalAlignment.Center;
        //        //    t.SetBinding(TextBlock.TextProperty, bind);
        //        //    t.SetBinding(TextBox.TextProperty, bind);
        //        //}
        //        #endregion
        //    };

        //    //Setear RowHeaders
        //    pgTotalTotal.addRowHeaderData((new RowHeaders("Test", new List<string>() { "Tiempo Implementacion", "Visitas Sugeridas", "NumRecursos", "NumIniciativas" })) as IPGridRowHeader);

        //    //CrearFreeze cols
        //    pgTotalTotal.addColumnFrezze("Labels", new List<string>() { "Tiempo Implementacion", "Visitas Sugeridas" }, true);
        //    pgTotalTotal.generateRowHeader();
        //    pgTotalTotal.generateFreezeCols();
        //    pgTotalTotal.generateRowData();

        //    this.setGrayFreezeColStyle(pgTotal);
        //}

        //private void setBlueHeaderStyle(Nav3.PGrid.PGrid p)
        //{
        //    //666666
        //    var topHeader = p._rightGrdHeader.Children.Cast<UIElement>().Where(i => Grid.GetRow(i) == 0);
        //    foreach (var t in topHeader)
        //    {
        //        BrushConverter bc = new BrushConverter();
        //        ((Border)t).Background = ((Brush)bc.ConvertFrom("#095ba6"));
        //        ((TextBlock)((Border)t).Child).Foreground = Brushes.White;
        //        ((TextBlock)((Border)t).Child).HorizontalAlignment = HorizontalAlignment.Center;
        //    }
        //    topHeader = p._rightGrdHeader.Children.Cast<UIElement>().Where(i => Grid.GetRow(i) == 1);
        //    foreach (var t in topHeader)
        //    {
        //        BrushConverter bc = new BrushConverter();
        //        ((Border)t).Background = ((Brush)bc.ConvertFrom("#5890c5"));
        //        ((TextBlock)((Border)t).Child).Foreground = Brushes.White;
        //        ((TextBlock)((Border)t).Child).HorizontalAlignment = HorizontalAlignment.Center;
        //    }
        //}

        //private void setGrayFreezeColStyle(Nav3.PGrid.PGrid p)
        //{
        //    //Poner estilos a columna congelada
        //    foreach (var r in p._leftGrdData.Children)
        //    {
        //        BrushConverter bc = new BrushConverter();

        //        ((Border)r).Background = ((Brush)bc.ConvertFrom("#858484"));
        //        ((Border)r).BorderThickness = new Thickness(0.1);
        //        ((TextBlock)((Border)r).Child).Foreground = Brushes.White;
        //    }
        //    foreach (var r in p._leftGrdHeader.Children)
        //    {
        //        BrushConverter bc = new BrushConverter();

        //        ((Border)r).Background = ((Brush)bc.ConvertFrom("#666666"));
        //        ((Border)r).BorderThickness = new Thickness(0.1);
        //        ((TextBlock)((Border)r).Child).Foreground = Brushes.White;
        //    }
        //}

        //public static ResourceDictionary SetDictionaryStyle(string path)
        //{
        //    ResourceDictionary rd = new ResourceDictionary();
        //    try
        //    {
        //        rd.Source = new Uri(path, UriKind.RelativeOrAbsolute);
        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //    return rd;
        //}



        //private void setColumnVisibility()
        //{
        //    double totalActualWidht = 0;
        //    foreach (PosInfoAttribute p in l)
        //    {
        //        if (p.orgSize == null)
        //        {
        //            p.orgSize = pg._leftGrdHeader.ColumnDefinitions[p.ColMap].Width.Value;
        //        }

        //        if (p.IsSelected)
        //        {
        //            pg._leftGrdHeader.ColumnDefinitions[p.ColMap].Width = new GridLength((double)p.orgSize);
        //            pg._leftGrdData.ColumnDefinitions[p.ColMap].Width = new GridLength((double)p.orgSize);
        //            totalActualWidht += (double)p.orgSize;
        //        }
        //        else
        //        {
        //            pg._leftGrdHeader.ColumnDefinitions[p.ColMap].Width = new GridLength(0, GridUnitType.Auto);
        //            pg._leftGrdData.ColumnDefinitions[p.ColMap].Width = new GridLength(0, GridUnitType.Auto);
        //        }

        //        var res = pg._leftGrdData.Children.Cast<UIElement>().Where(i => Grid.GetColumn(i) == p.ColMap);
        //        foreach (var r in res)
        //        {
        //            ((Border)r).Visibility = (p.IsSelected) ? Visibility.Visible : Visibility.Collapsed;
        //        }
        //        var res2 = pg._leftGrdHeader.Children.Cast<UIElement>().Where(i => Grid.GetColumn(i) == p.ColMap);
        //        foreach (var r2 in res2)
        //        {
        //            ((Border)r2).Visibility = (p.IsSelected) ? Visibility.Visible : Visibility.Collapsed;
        //        }
        //    }

        //    //pgTotal._leftGrdData.ColumnDefinitions[0].Width = new GridLength(this.posColumnWidht + totalActualWidht);
        //    //-----------------
        //    BrushConverter bc = new BrushConverter();

        //    ScrollViewer sv = (ScrollViewer)pg._leftGrdData.Parent;
        //    sv.Width = 170;
        //    sv.Background = ((Brush)bc.ConvertFrom("#858484"));
        //    ScrollViewer svh = (ScrollViewer)pg._leftGrdHeader.Parent;
        //    svh.Width = 170;
        //    svh.Background = ((Brush)bc.ConvertFrom("#666666"));
        //}

        public void setUnidVersion(long version)
        {
            this.currentUnidVersion = version;

            //FdvGridViewModel vm = this.DataContext as FdvGridViewModel;
            //if (vm != null)
            //{
            //    vm.FdvVersion.Unid = version;
            //}

            //this.currentFdvVersion = FdvVersion.GetFdvVersionByUnid(version);
            //if (this.currentFdvVersion != null)
            //{
            //    if (this.currentFdvVersion.DatePublished != DateTime.MinValue)
            //    {
            //        this.lblStatus.Content = "Versión Publicada";
            //        this.btnPublicar.IsEnabled = false;
            //        //this.btnUndoPublish.IsEnabled = true;
            //        //this.btnUndoPublish.Visibility = Visibility.Visible;
            //    }
            //    else
            //    {
            //        this.lblStatus.Content = "";
            //        //this.btnUndoPublish.IsEnabled = false;
            //        //this.btnUndoPublish.Visibility = Visibility.Collapsed;
            //    }

            //    if (this.currentFdvVersion.HqDateClosed != DateTime.MinValue)
            //    {
            //        this.lblStatus.Content = "Versión Cerrada";
            //        //this.modeVersiónCerrada();
            //    }
            //}
        }

        //public void setUnidVersion(long version)
        //{
        //    this.currentFdvVersion = FdvVersion.GetFdvVersionByUnid(version);
        //    if (this.currentFdvVersion != null)
        //    {
        //        if (this.currentFdvVersion.DatePublished != DateTime.MinValue)
        //        {
        //            this.lblStatus.Content = "Versión Publicada";
        //            this.btnPublicar.IsEnabled = false;
        //            //this.btnUndoPublish.IsEnabled = true;
        //            //this.btnUndoPublish.Visibility = Visibility.Visible;
        //        }
        //        else
        //        {
        //            this.lblStatus.Content = "";
        //            //this.btnUndoPublish.IsEnabled = false;
        //            //this.btnUndoPublish.Visibility = Visibility.Collapsed;
        //        }

        //        if (this.currentFdvVersion.HqDateClosed != DateTime.MinValue)
        //        {
        //            this.lblStatus.Content = "Versión Cerrada";
        //            //this.modeVersiónCerrada();
        //        }
        //    }
        //}

        //public void modeVersiónCerrada()
        //{
        //    this.btnGuardar.IsEnabled = false;
        //    this.btnPublicar.IsEnabled = false;
        //    this.dataGridRightData.IsReadOnly = true;
        //    this.btnBorrarRecurso.IsEnabled = false;

        //    this.btnGuardar.Visibility = Visibility.Collapsed;
        //    this.btnPublicar.Visibility = Visibility.Collapsed;
        //    this.btnBorrarRecurso.Visibility = Visibility.Collapsed;

        //    //this.btnUndoPublish.IsEnabled = false;
        //    //this.btnUndoPublish.Visibility = Visibility.Collapsed;
        //}

        public void setTerritorio(string territorio)
        {
            this.currentPositionCode = territorio;
        }

        private void publish()
        {
            FdvGridViewModel vm = this.GetViewModel();

            if (vm != null)
            {
                if (vm.FdvVersion.Unid <= 0)
                {
                    MessageBox.Show("No existe una versión seleccionada o no hay datos para publicar.", "Publicación FDV", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }
            }

            //FdvVersion version = FdvVersion.GetFdvVersionByUnid(this.currentUnidVersion);
            //if (version == null)
            //{
            //    MessageBox.Show("No existe una versión seleccionada o no hay datos para publicar.", "Publicación FDV", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            //    return;
            //}

            //if (version.DatePublished != DateTime.MinValue)
            //{
            //    if (MessageBox.Show("La versión ya ha sido previamente publicada. Si contunúa, se volverán a publicar los recursos modificados. \n¿Desea continuar?", "Advertencia", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            //    {
            //        VMPublish vm = new VMPublish(this.capsFdv.ObCollPFDV, this.currentUnidVersion, Window.GetWindow(this));
            //        DlgSave ds = new DlgSave();
            //        ds.DataContext = vm;
            //        ds.Owner = Application.Current.Windows[0];
            //        //vm.Message = "Fin de la publicación.";
            //        vm.start();
            //        ds.ShowDialog();
            //    }//if continue
            //}//if idpublish
            //else
            //{
            //objPubFDV.Publish();
            //VMPublish vm = new VMPublish(this.capsFdv.ObCollPFDV, this.currentUnidVersion, Window.GetWindow(this));

            VMPublish vm2 = new VMPublish(null, vm.FdvVersion.Unid, Window.GetWindow(this), this.lblStatus, this.btnPublicar);
            DlgSave ds = new DlgSave();
            ds.DataContext = vm2;
            ds.Owner = Application.Current.Windows[0];
            //vm.Message = "Fin de la publicación.";
            vm2.start();
            ds.ShowDialog();

            //}
        }

        //private void calculateGridInd()
        //{
        //    foreach (CapFDVIndicador re in this.m.entry)
        //    {
        //        CapFDVIndicador cfi = m.Calculate(re.Pos.idPos, capsFdv);
        //        re.Iniciativas = cfi.Iniciativas;
        //        re.NumIniciativas = cfi.NumIniciativas;
        //        re.TiempoImplementacion = cfi.TiempoImplementacion;
        //        re.VisitasSugeridas = cfi.VisitasSugeridas;
        //        re.NumRecursos = cfi.NumRecursos;
        //    }
        //}

        #region ISave Interface
        public void save()
        {
            if (this.currentUnidVersion > 0 && !string.IsNullOrEmpty(this.currentPositionCode) )
            {
                FdvGridViewModel vm = this.GetViewModel();

                if (vm != null)
                {
                    if (vm.SaveCommand.CanExecute(null))
                    {
                        vm.SaveCommand.Execute(null);
                    }
                    //if (this.currentUnidVersion.DatePublished != DateTime.MinValue)
                    //{
                    //    var res = MessageBox.Show(Application.Current.Windows[0], "Si guarda la versión se publicarán los recursos que hayan sido modificados ¿Esta seguro de guardar?", "Guardar versión publicada", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
                    //    if (res == MessageBoxResult.Yes)
                    //    {
                    //        this.openSaveDialog();

                    //        this.publish();
                    //    }
                    //}
                    //else
                    //{
                    //    this.openSaveDialog();
                    //}
                }
            }
        }

        public void loadData()
        {
            //this.createModelObjects();
        }
        #endregion

        private void openSaveDialog()
        {
            ViewModelSaveCapFdv vm = new ViewModelSaveCapFdv(this.capsFdv.ObCollPFDV, this.currentUnidVersion);
            DlgSave ds = new DlgSave();
            ds.DataContext = vm;
            ds.Owner = Application.Current.Windows[0];
            ds.ShowDialog();
            vm.start();
            this.IsModified = false;
        }

        public void loadControl()
        {
            if (!String.IsNullOrEmpty(this.currentPositionCode) && this.currentUnidVersion>0)
            {
                //this.currentUnidVersion = this.currentFdvVersion.UnidFdvBgtVersion;

                this.DataContext = new FdvGridViewModel(
                    new FdvDataMapper(), 
                    this.currentUnidVersion, 
                    new HelperRePublishConfirm(),
                    new HelperSaveDialog(),
                    this.currentPositionCode,
                    this
                );

                FdvGridViewModel vm = this.DataContext as FdvGridViewModel;
                if (System.Windows.Application.Current != null)
                {
                    vm.dp = System.Windows.Application.Current.Dispatcher;

                }
                vm.PropertyChanged += delegate(object s, PropertyChangedEventArgs e)
                {
                    if (e.PropertyName.ToLower() == "ismodified")
                    {
                        this.IsModified = ((FdvGridViewModel)s).IsModified;
                    }
                };

                vm.BorrarFiltrosCommand.CommandExecuted += delegate(object sBf, System.EventArgs eBf)
                {
                    foreach (var c in this.spBotDataHeaderContainer.Children)
                    {
                        try
                        {
                            Border brd = c as Border;

                            if (brd!=null)
                            {
                                StackPanel sp = brd.Child as StackPanel;
                                if (sp != null)
                                {
                                    Image img = sp.Children[0] as Image;
                                    if (img != null)
                                    {
                                        img.Visibility = Visibility.Hidden;
                                    }
                                } 
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                };

                this.LoadGrid(this.DataContext as FdvGridViewModel);
                this.CreateHeaders(this.DataContext as FdvGridViewModel);
                this.SetColumnsWidth(this.DataContext as FdvGridViewModel);
                //this.posColumnWidht = 170;// 110;

                //this.createModelObjects();

                //if (this.capsFdv.ObCollPFDV.Count > 0)
                //{
                //    this.createDataGridDataFDV();
                //    this.createDataGrid();
                //    this.CreateDataGridIndicadores();
                //    this.CreateDataGridTotales();
                //    this.CreateDataGridTotalesTotales();
                //    this.setColumnVisibility();
                //    this.cmb.ItemsSource = l;
                //}
            }
        }//

        //Grid Function
        private void LoadGrid(FdvGridViewModel fdvGridViewModel)
        {
            this.dgData.Columns.Clear();
            this.dgDataTotalRec.Columns.Clear();

            foreach (Prueba.Model.Recurso r in fdvGridViewModel.Recursos)
            {
                //Se definie el binding de datos
                Binding bindingCol = new Binding("Cols[" + r.RecursoId + "].Cantidad");
                bindingCol.Mode = BindingMode.TwoWay;
                bindingCol.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;

                //Crear multibinding
                MultiBinding mb = new MultiBinding();
                Binding bgColColor = new Binding("Cols[" + r.RecursoId + "].Pos.IsOneRuleExceded");
                bgColColor.Mode = BindingMode.TwoWay;
                mb.Bindings.Add(bgColColor);
                bgColColor = new Binding("Cols[" + r.RecursoId + "].Recurso.IsMaximoAsignadoEx");
                bgColColor.Mode = BindingMode.TwoWay;
                mb.Bindings.Add(bgColColor);
                mb.Converter = new MultiBoolColorConverter();

                //Crear estilo para pintar celda en rojo cuando la regla de max recurso o max iniciativa es rebasada
                Style s = new Style();
                s.TargetType = typeof(DataGridCell);
                s.Setters.Add(new Setter
                {
                    Property = DataGridCell.BackgroundProperty,
                    Value = mb
                });
                s.Setters.Add(new Setter
                {
                    Property = TextBlock.TextAlignmentProperty,
                    Value = TextAlignment.Center
                });
                s.Setters.Add(new Setter()
                {
                    Property = DataGridCell.ForegroundProperty,
                    Value = Brushes.Black
                });

                //Agregar columna al datagrid
                this.dgData.Columns.Add(
                    new DataGridTextColumn()
                    {
                        Header = r.RecursoId,
                        Binding = bindingCol,
                        Width = 110,
                        CellStyle=s
                    }
                );

                //Crear estilo para pintar celda en rojo cuando la regla de max recurso o max iniciativa es rebasada
                s = new Style();
                bgColColor = new Binding("Recursos[" + r.RecursoId + "].Recurso.IsMaximoAsignadoEx");
                bgColColor.Mode = BindingMode.TwoWay;
                bgColColor.Converter = new RuleExcededBgkColorConverter();
                s.TargetType = typeof(DataGridCell);
                s.Setters.Add(new Setter
                {
                    Property = DataGridCell.BackgroundProperty,
                    Value = bgColColor
                });
                s.Setters.Add(new Setter
                {
                    Property = TextBlock.TextAlignmentProperty,
                    Value = TextAlignment.Center
                });
                s.Setters.Add(new Setter()
                {
                    Property = DataGridCell.ForegroundProperty,
                    Value = Brushes.Black
                });

                //Agregar columna de totales por Recurso
                Binding bindingTotalCol = new Binding("Recursos[" + r.RecursoId + "].Cantidad");
                bindingTotalCol.Mode = BindingMode.OneWay;
                this.dgDataTotalRec.Columns.Add(
                    new DataGridTextColumn()
                    {
                        Header = r.RecursoId,
                        Binding = bindingTotalCol,
                        Width = 110,
                        CellStyle = s
                    }
                );
            }

            //Crear estilo para totales verticales
            Style s2 = new Style();
            Binding bgColColor2 = new Binding("Pos.IsOneRuleExceded");
            bgColColor2.Mode = BindingMode.TwoWay;
            bgColColor2.Converter = new RuleExcededBgkColorConverter();
            s2.TargetType = typeof(DataGridCell);
            s2.Setters.Add(new Setter
            {
                Property = DataGridCell.BackgroundProperty,
                Value = bgColColor2
            });
            s2.Setters.Add(new Setter
            {
                Property = TextBlock.TextAlignmentProperty,
                Value = TextAlignment.Center
            });
            s2.Setters.Add(new Setter()
            {
                Property = DataGridCell.ForegroundProperty,
                Value = Brushes.Black
            });

            //Enlazar a datagrid de totales
            foreach (DataGridColumn dc in this.dgDataInd.Columns)
            {
                dc.CellStyle = s2;
            }
        }//endfunc

        #region Header Functions
        private void CreateHeaders(FdvGridViewModel fdvGridViewModel)
        {
            this.spLeftHeaderContainer.Children.Clear();
            this.spTopDataHeaderContainer.Children.Clear();
            this.spBotDataHeaderContainer.Children.Clear();

            this.CreateLeftHeader(fdvGridViewModel);
            this.CreateDataHeader(fdvGridViewModel);
            this.CreateRightHeader(fdvGridViewModel);
        }

        private void CreateLeftHeader(FdvGridViewModel fdvGridViewModel)
        {
            //Se toman las columnas definadas en el DataGrid de de POS
            int index = 0;
            foreach (DataGridColumn col in this.dgDataPos.Columns)
            {
                //Crear celda y poner estilo para el encabezado
                Border brd = this.createReadCell(col.Header.ToString());
                brd.Width = fdvGridViewModel.HeaderModel.PosHeaderWidth;
                brd.Height = fdvGridViewModel.HeaderModel.MergeHeaderHeight;
                this.SetGrayCellStyle(ref brd);

                //Binding a la propiedad
                Binding bind = new Binding("PosCols["+index.ToString()+"].IsVisible");
                bind.Mode = BindingMode.TwoWay;
                bind.Converter = this.FindResource("columnVisibleConverter") as IValueConverter;

                brd.SetBinding(Border.VisibilityProperty, bind);

                //Agregar al stack
                this.spLeftHeaderContainer.Children.Add(brd);
                index++;
            }
        }

        private void CreateDataHeader(FdvGridViewModel fdvGridViewModel)
        {
            //Para agregar los encabezados la colección de recursos debe estar previamente ordenada por Iniciativa y por Recurso
            //Se asume que para el uso en esta función, la colección Recursos, ya ha sido ordenada

            if (fdvGridViewModel.Recursos.Count == 0)
            {
                throw new Exception("Versión sin datos. \n La versión seleccionada no contiene información o ha sido cancelada");
            }
            
            
            string curIniciativa = fdvGridViewModel.Recursos[0].Iniciativa.IniciativaId;
            double mergeWidthCount = 0;
            foreach (Prueba.Model.Recurso r in fdvGridViewModel.Recursos)
            {
                //Agregar celda de iniciativa
                if (curIniciativa != r.Iniciativa.IniciativaId)
                {
                    //Crear celda y poner estilo para el encabezado
                    Border brd = this.createReadCell(curIniciativa);
                    brd.Width = fdvGridViewModel.HeaderModel.HeaderWidth * (mergeWidthCount == 0 ? 1d : mergeWidthCount);
                    brd.Height = fdvGridViewModel.HeaderModel.HeaderHeight;
                    brd.ToolTip = r.Iniciativa.IniciativaName;
                    this.SetBlueCellStyle(ref brd);
                    this.spTopDataHeaderContainer.Children.Add(brd);

                    curIniciativa = r.Iniciativa.IniciativaId;
                    mergeWidthCount = 0;
                }
                mergeWidthCount++;

                //Agregar celda para Recurso
                Border brdRecurso = this.createReadCellFilter(r.RecursoId,fdvGridViewModel.HeaderModel);
                brdRecurso.Width = fdvGridViewModel.HeaderModel.HeaderWidth;
                brdRecurso.Height = fdvGridViewModel.HeaderModel.HeaderHeight;
                brdRecurso.ToolTip = r.RecursoName + " (Click para filtrar por recurso)";
                brdRecurso.Cursor = Cursors.Hand;
                brdRecurso.IsHitTestVisible = true;
                brdRecurso.MouseDown += new MouseButtonEventHandler(brdRecurso_MouseDown);
                this.SetLightBlueCellStyleFilter(ref brdRecurso);
                this.spBotDataHeaderContainer.Children.Add(brdRecurso);
            }

            if (curIniciativa == fdvGridViewModel.Recursos.Last().Iniciativa.IniciativaId)
            {
                //Crear celda y poner estilo para el encabezado
                Border brd = this.createReadCell(curIniciativa);
                brd.Width = fdvGridViewModel.HeaderModel.HeaderWidth * (mergeWidthCount == 0 ? 1d : mergeWidthCount);
                brd.Height = fdvGridViewModel.HeaderModel.HeaderHeight;
                brd.ToolTip = fdvGridViewModel.Recursos.Last().Iniciativa.IniciativaName;
                this.SetBlueCellStyle(ref brd);
                this.spTopDataHeaderContainer.Children.Add(brd);
            }
        }

        private void CreateRightHeader(FdvGridViewModel fdvGridViewModel)
        {
            //Se toman las columnas definadas en el DataGrid de los totales o indicadores
            foreach (DataGridColumn col in this.dgDataInd.Columns)
            {
                //Crear celda y poner estilo para el encabezado
                Border brd = this.createReadCell(col.Header.ToString());
                brd.Width = fdvGridViewModel.HeaderModel.TotalHeaderWidth;
                brd.Height = fdvGridViewModel.HeaderModel.TotalHeaderHeight;
                this.SetLightBlueCellStyle(ref brd);

                //Agregar al stack
                this.spBotRightHeaderContainer.Children.Add(brd);
            }

            //Agregar el título indicadores
            //Crear celda y poner estilo para el encabezado
            Border brdInd = this.createReadCell("Indicadores");
            brdInd.Width = fdvGridViewModel.HeaderModel.TotalHeaderWidth * 4;
            brdInd.Height = fdvGridViewModel.HeaderModel.TotalHeaderHeight;
            this.SetBlueCellStyle(ref brdInd);
            this.spTopRightHeaderContainer.Children.Add(brdInd);
        }
        #endregion

        #region Cell Functions
        private Border createReadCell(string text)
        {
            Border brdSubHeader = new Border();
            brdSubHeader.BorderThickness = new System.Windows.Thickness(0.5);
            brdSubHeader.BorderBrush = Brushes.Gray;
            brdSubHeader.Focusable = true;
            brdSubHeader.IsHitTestVisible = true;

            TextBlock txtBlock = new TextBlock();
            txtBlock.Text = text;

            txtBlock.HorizontalAlignment = HorizontalAlignment.Stretch;

            brdSubHeader.Child = txtBlock;

            return brdSubHeader;
        }

        private Border createReadCellFilter(string text,HeaderModel hm)
        {
            Border brdSubHeader = new Border();
            brdSubHeader.BorderThickness = new System.Windows.Thickness(0.5);
            brdSubHeader.BorderBrush = Brushes.Gray;
            brdSubHeader.Focusable = true;
            brdSubHeader.IsHitTestVisible = true;

            TextBlock txtBlock = new TextBlock();
            txtBlock.Text = text;
            txtBlock.VerticalAlignment = VerticalAlignment.Center;
            txtBlock.Cursor = Cursors.Hand;
            //txtBlock.HorizontalAlignment = HorizontalAlignment.Stretch;
            //txtBlock.Margin = new Thickness(0);

            Image img = new Image();
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri("images/filterIcon.png",UriKind.Relative);
            bi.EndInit();
            img.Width = 13;
            img.Height = 10;
            img.Source = bi;
            img.Stretch = Stretch.Fill;
            img.Visibility = Visibility.Hidden;
            //img.HorizontalAlignment = HorizontalAlignment.Right;
            //img.VerticalAlignment = VerticalAlignment.Top;
            //Panel.SetZIndex(img, 10);
            //img.Margin = new Thickness(-40, 0, 0, 0);

            StackPanel sp = new StackPanel();
            sp.HorizontalAlignment = HorizontalAlignment.Stretch;
            sp.VerticalAlignment = VerticalAlignment.Stretch;
            sp.Orientation = Orientation.Horizontal;
            sp.Children.Add(img);
            sp.Children.Add(txtBlock);
            

            brdSubHeader.Child = sp;

            return brdSubHeader;
        }

        private void SetGrayCellStyle(ref Border r)
        {
            //Poner estilos a columna congelada
            //foreach (var r in p._leftGrdData.Children)
            //{
            //    BrushConverter bc = new BrushConverter();

            //    ((Border)r).Background = ((Brush)bc.ConvertFrom("#858484"));
            //    ((Border)r).BorderThickness = new Thickness(0.1);
            //    ((TextBlock)((Border)r).Child).Foreground = Brushes.White;
            //}
            BrushConverter bc = new BrushConverter();

            ((Border)r).Background = ((Brush)bc.ConvertFrom("#666666"));
            ((Border)r).BorderThickness = new Thickness(0.1);
            ((TextBlock)((Border)r).Child).Foreground = Brushes.White;
        }//endfunc

        private void SetBlueCellStyle(ref Border r)
        {
            BrushConverter bc = new BrushConverter();
            ((Border)r).Background = ((Brush)bc.ConvertFrom("#095ba6"));
            ((TextBlock)((Border)r).Child).Foreground = Brushes.White;
            ((TextBlock)((Border)r).Child).HorizontalAlignment = HorizontalAlignment.Center;
        }//endfunc

        private void SetLightBlueCellStyle(ref Border r)
        {
            BrushConverter bc = new BrushConverter();
            ((Border)r).Background = ((Brush)bc.ConvertFrom("#5890c5"));
            ((TextBlock)((Border)r).Child).Foreground = Brushes.White;
            ((TextBlock)((Border)r).Child).HorizontalAlignment = HorizontalAlignment.Center;
        }

        private void SetLightBlueCellStyleFilter(ref Border r)
        {
            BrushConverter bc = new BrushConverter();
            ((Border)r).Background = ((Brush)bc.ConvertFrom("#5890c5"));
            ((TextBlock)((StackPanel)((Border)r).Child).Children[1]).Foreground = Brushes.White;
            ((TextBlock)((StackPanel)((Border)r).Child).Children[1]).HorizontalAlignment = HorizontalAlignment.Center;
        }
        #endregion

        /// <summary>
        /// Establece el ancho de las columnas de todos grids tomando los datos del ancho del view model
        /// </summary>
        /// <param name="fdvGridViewModel"></param>
        private void SetColumnsWidth(FdvGridViewModel fdvGridViewModel)
        {
            //Para columna 1
            foreach (DataGridColumn col in this.dgDataPos.Columns)
            {
                col.Width = fdvGridViewModel.HeaderModel.PosHeaderWidth;
            }
            foreach (DataGridColumn col in this.dgDataTotalRecTitle.Columns)
            {
                col.Width = fdvGridViewModel.HeaderModel.PosHeaderWidth;
            }

            //Para columna 2
            foreach (DataGridColumn col in this.dgData.Columns)
            {
                col.Width = fdvGridViewModel.HeaderModel.HeaderWidth;
            }
            foreach (DataGridColumn col in this.dgDataTotalRec.Columns)
            {
                col.Width = fdvGridViewModel.HeaderModel.HeaderWidth;
            }

            //Para columna 3
            foreach (DataGridColumn col in this.dgDataInd.Columns)
            {
                col.Width = fdvGridViewModel.HeaderModel.TotalHeaderWidth;
            }
            foreach (DataGridColumn col in this.dgDataTotal.Columns)
            {
                col.Width = fdvGridViewModel.HeaderModel.TotalHeaderWidth;
            }
        }//endfunc  

        #region EventHandlers
        //private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
        //{
        //    int rowHeight = 22;
        //    int columnWidth = 110;

        //    ScrollViewer scroll = new ScrollViewer();
        //    //Obtener el scrollviewer del datagrid
        //    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(this.dataGridRightData); i++)
        //    {
        //        if (VisualTreeHelper.GetChild(this.dataGridRightData, i) is Border)
        //        {
        //            Border brd = VisualTreeHelper.GetChild(this.dataGridRightData, i) as Border;

        //            for (int j = 0; j < VisualTreeHelper.GetChildrenCount(brd); j++)
        //            {
        //                if (VisualTreeHelper.GetChild(brd, j) is ScrollViewer)
        //                {
        //                    scroll =
        //              (ScrollViewer)(VisualTreeHelper.GetChild(brd, j));
        //                    Console.WriteLine(scroll.HorizontalOffset);
        //                    break;
        //                }
        //            }
        //        }
        //    }

        //    if (sender.GetType() == typeof(DataGrid))
        //    {
        //        //Sincronizr scroll de datos pos verticalmente
        //        this.scrollLeftData.ScrollToVerticalOffset(scroll.VerticalOffset * 22);
        //        this.scrollRightDataKpi.ScrollToVerticalOffset(scroll.VerticalOffset * 22);

        //        this.scrollRightDataTotal.ScrollToHorizontalOffset(scroll.HorizontalOffset);
        //        this.scrollRightHeader.ScrollToHorizontalOffset(scroll.HorizontalOffset);
        //    }
        //    else
        //    {
        //        //Scroll para los datos
        //        scroll.ScrollToVerticalOffset(Math.Round((sender as ScrollViewer).VerticalOffset / rowHeight, MidpointRounding.AwayFromZero));
        //        this.scrollLeftData.ScrollToVerticalOffset((sender as ScrollViewer).VerticalOffset);
        //        this.scrollRightDataKpi.ScrollToVerticalOffset((sender as ScrollViewer).VerticalOffset);

        //        this.scrollRightDataTotal.ScrollToHorizontalOffset(scroll.HorizontalOffset);
        //        this.scrollRightHeader.ScrollToHorizontalOffset(scroll.HorizontalOffset);
        //        //scroll.ScrollToHorizontalOffset(scroll.HorizontalOffset);

        //        //this.scrollRightHeader.ScrollToHorizontalOffset((sender as ScrollViewer).HorizontalOffset);
        //        //this.scrollRightDataTotal.ScrollToHorizontalOffset((sender as ScrollViewer).HorizontalOffset);

        //        //---------------- 2012-12-10
        //        if ((sender as ScrollViewer).Name == "scrollLeftData")
        //            this.scrollLeftHeader.ScrollToHorizontalOffset((sender as ScrollViewer).HorizontalOffset);
        //        //---------------------------
        //        //scroll.ScrollToVerticalOffset((sender as ScrollViewer).VerticalOffset);

        //        //if (this.scrollLeftData.VerticalOffset > this.scrollRightData.VerticalOffset)
        //        //{
        //        //    this.scrollLeftData.ScrollToVerticalOffset(this.scrollRightData.VerticalOffset);
        //        //}
        //    }

        //}

        private void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //Se utiliza para que el selected item siempre sea nulo
            int x;
            x = 0;
            cmb.SelectedItem = null;
        }

        private void CheckBox_SourceUpdated(object sender, DataTransferEventArgs e)
        {
            //this.setColumnVisibility();
        }

        //private void btnPublicar_Click(object sender, RoutedEventArgs e)
        //{
        //    //this.openSaveDialog();
        //    ////PublishFDV objPubFDV = new PublishFDV(this.currentUnidVersion);
        //    //this.publish();
        //}

        private void btnGuardar_Click(object sender, RoutedEventArgs e)
        {
            this.save();
        }

        private void btnBorrarRecurso_Click(object sender, RoutedEventArgs e)
        {

                DlgElegirRecurso dlgElegirRecurso = new DlgElegirRecurso();
                dlgElegirRecurso.recursos = new ObservableCollection<RecursoWithCheck>();

                FdvGridViewModel vm = this.DataContext as FdvGridViewModel;
                if (!vm.FdvVersion.IsClosed)
                {
                    if (vm != null)
                    {
                        foreach (Prueba.Model.Recurso r in vm.Recursos)
                        {
                            dlgElegirRecurso.recursos.Add(new RecursoWithCheck(new BAL.EstRec.Recurso() { idRecurso = r.RecursoId, recurso = r.RecursoName }));
                        }
                        dlgElegirRecurso.listView.ItemsSource = dlgElegirRecurso.recursos;
                    }

                    dlgElegirRecurso.Closed += delegate(object dlgSender, System.EventArgs args)
                    {
                        if (dlgElegirRecurso.isOk)
                        {
                            List<BAL.EstRec.Recurso> recursos = dlgElegirRecurso.getSelectedRecursos();
                            foreach (RowFdv rfdv in vm.Rows)
                            {
                                foreach (BAL.EstRec.Recurso item in recursos)
                                {
                                    if (rfdv.Cols[item.idRecurso].Cantidad > 0)
                                    {
                                        rfdv.Cols[item.idRecurso].Cantidad = 0;
                                    }
                                }
                            }
                        }//endif
                    };
                    dlgElegirRecurso.ShowDialog(); 
                }
            
        }

        private void btnBuscar_Click(object sender, RoutedEventArgs e)
        {
            FdvGridViewModel vm = this.DataContext as FdvGridViewModel;
            if (vm!=null)
            {
                DlgBuscar buscar = new DlgBuscar();
                buscar.Owner = Window.GetWindow(this);
                buscar.ShowDialog();

                if (buscar.isOk)
                {
                    string idPos = buscar.txtClavePos.Text.ToLower();
                    string nombrePos = buscar.txtNombrePos.Text.ToLower();
                    bool IsFound = false;

                    if (!String.IsNullOrEmpty(idPos))
                    {
                        foreach (RowFdv rf in vm.Rows)
                        {
                            if (rf.Pos.PosId.ToLower().Contains(idPos))
                            {
                                vm.SelectedRowFdv = rf;
                                this.dgData.ScrollIntoView(vm.SelectedRowFdv);
                                IsFound = true;
                                break;
                            }
                        }
                    }//endif

                    if (!String.IsNullOrEmpty(nombrePos))
                    {
                        foreach (RowFdv rf in vm.Rows)
                        {
                            if (rf.Pos.PosName.ToLower().Contains(nombrePos))
                            {
                                vm.SelectedRowFdv = rf;
                                this.dgData.ScrollIntoView(vm.SelectedRowFdv);
                                IsFound = true;
                                break;
                            }
                        }
                    }//endif

                    if (!IsFound)
                    {
                        MessageBox.Show("No se encontró coincidencia en la búsqueda", "Búsqueda", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
                    }
                }//endif 
            }//endif
        }//endfunc

        //Evento de MouseDown en las celdas de encabezado de recurso para filtrar la informaci{on
        void brdRecurso_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                Border r = sender as Border;
                if (r != null)
                {
                    TextBlock txt = ((StackPanel)r.Child).Children[1] as TextBlock;
                    if (txt != null)
                    {
                        FiltroFdvViewModel vm = new FiltroFdvViewModel(this.DataContext as FdvGridViewModel, txt.Text);
                        DlgFiltroFdvView view = new DlgFiltroFdvView();
                        view.DataContext = vm;
                        view.ShowDialog();

                        if (vm.IsClean)
                        {
                            ((Image)((StackPanel)r.Child).Children[0]).Visibility = Visibility.Hidden;
                        }
                        if (vm.IsFilter)
                        {
                            ((Image)((StackPanel)r.Child).Children[0]).Visibility = Visibility.Visible;
                        }
                    }
                }
            }
        }


        //private void dataGridRightData_LoadingRow(object sender, DataGridRowEventArgs e)
        //{
        //    //e.Row.Background
        //    //Crear binding para background de color
        //    Prueba.Model.RecursoIndexer ri = e.Row.DataContext as Prueba.Model.RecursoIndexer;
        //    if (ri != null)
        //    {
        //        Binding bgkColor = new Binding("IsRuleExceded");
        //        bgkColor.Source = ri.indicador;
        //        bgkColor.Mode = BindingMode.TwoWay;
        //        bgkColor.Converter = new RuleExcededBgkColorConverter();
        //        e.Row.SetBinding(DataGridRow.BackgroundProperty, bgkColor);

        //    }

        //}

        private void btnUndoPublish_Click(object sender, RoutedEventArgs e)
        {
            //if (!(this.currentUnidVersion > 0))
            //    return;

            //if (this.currentFdvVersion.DatePublished > DateTime.MinValue && this.currentFdvVersion.HqDateClosed == DateTime.MinValue)
            //{
            //    if (MessageBox.Show("¿Está seguro de borrar la publicación de ésta ventana?", "Panel de actividades", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
            //    {
            //        AppConfs cnfs = new AppConfs();

            //        //UndoPublishFDV undo = new UndoPublishFDV(this.currentUnidVersion.ToString(), cnfs);
            //        //undo.UndoFDVPublish();
            //        VMUndoPublish undo = new VMUndoPublish(this.currentUnidVersion.ToString(), this.lblStatus, this.btnUndoPublish);

            //        DlgSave ds = new DlgSave();
            //        ds.DataContext = undo;
            //        ds.Owner = Application.Current.Windows[0];
            //        undo.start();
            //        ds.ShowDialog();

            //    }//if
            //}
        }
        #endregion

        private void dgDataPos_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (sender != null && sender.GetType() == typeof(DataGrid))
            {
                ScrollViewer svTarget = this.GetScrollFromDataGrid(sender as DataGrid);
                //Sincronizr scroll de datos pos verticalmente
                ScrollViewer svPos = this.GetScrollFromDataGrid(this.dgDataPos);
                ScrollViewer svPosData = this.GetScrollFromDataGrid(this.dgData);
                ScrollViewer svPosInd = this.GetScrollFromDataGrid(this.dgDataInd);
                ScrollViewer svDataTotalRec = this.GetScrollFromDataGrid(this.dgDataTotalRec);

                //Scroll Vertical
                svPos.ScrollToVerticalOffset(svTarget.VerticalOffset);
                svPosData.ScrollToVerticalOffset(svTarget.VerticalOffset);
                svPosInd.ScrollToVerticalOffset(svTarget.VerticalOffset);

                //Scroll Horizontal
                if ((sender as DataGrid).Name == "dgDataPos")
                {
                    this.scrollLeftHeader.ScrollToHorizontalOffset(svTarget.HorizontalOffset);
                }

                if ((sender as DataGrid).Name == "dgData" || (sender as DataGrid).Name =="dgDataTotalRec")
                {
                    svPosData.ScrollToHorizontalOffset(svTarget.HorizontalOffset);
                    svDataTotalRec.ScrollToHorizontalOffset(svTarget.HorizontalOffset);
                    this.scrollDataHeader.ScrollToHorizontalOffset(svTarget.HorizontalOffset);
                }
            }
        }

        private ScrollViewer GetScrollFromDataGrid(DataGrid dg)
        {
            ScrollViewer scroll = new ScrollViewer();
            //Obtener el scrollviewer del datagrid
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dg); i++)
            {
                if (VisualTreeHelper.GetChild(dg, i) is Border)
                {
                    Border brd = VisualTreeHelper.GetChild(dg, i) as Border;

                    for (int j = 0; j < VisualTreeHelper.GetChildrenCount(brd); j++)
                    {
                        if (VisualTreeHelper.GetChild(brd, j) is ScrollViewer)
                        {
                            scroll =
                      (ScrollViewer)(VisualTreeHelper.GetChild(brd, j));
                            Console.WriteLine(scroll.HorizontalOffset);
                            break;
                        }
                    }
                }
            }
            return scroll;
        }

        public FdvGridViewModel GetViewModel()
        {
            FdvGridViewModel vm = null;

            vm = this.DataContext as FdvGridViewModel;

            return vm;
        }

        private void dgData_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            
            if (e.EditAction == DataGridEditAction.Commit && dgData.SelectionUnit == DataGridSelectionUnit.FullRow)
            {
                if (Keyboard.IsKeyDown(Key.Enter) || Keyboard.IsKeyDown(Key.Return))
                {
                    // get the row and column indexes of the currently selected cell
                    int currentColIndex = dgData.Columns.IndexOf(dgData.CurrentColumn),
                        currentRowIndex = dgData.Items.IndexOf(e.Row.Item);
                    var rowToSelect = dgData.Items[currentRowIndex]; // get the next row

                    FdvGridViewModel vm = this.GetViewModel() as FdvGridViewModel;
                    
                    
                    
                    //var colToSelect = dgData.Columns[currentColIndex];
                    //int rowIndex = dgData.Items.IndexOf(rowToSelect);
                    //// select the new cell
                    ////dgData.SelectedCells.Clear();
                    //dgData.SelectedCells.Add(new DataGridCellInfo(rowToSelect, colToSelect));
                    this.Dispatcher.BeginInvoke(new DispatcherOperationCallback((param) =>
                    {
                        // get the new cell, set focus, then open for edit
                        if (vm != null)
                        {
                            vm.SelectedRowFdv = rowToSelect as RowFdv;
                        }
                        this.dgData.ScrollIntoView(vm.SelectedRowFdv);
                        
                        this.dgData.BeginEdit();

                        return null;
                    }), DispatcherPriority.Background, new object[] { null });
                }
            }
        }

        public void Publish()
        {
            FdvGridViewModel vm = this.GetViewModel();
            VMPublish vm2 = new VMPublish(null, vm.FdvVersion.Unid, Window.GetWindow(this), this.lblStatus, this.btnPublicar);
            DlgSave ds = new DlgSave();
            ds.DataContext = vm2;
            ds.Owner = Application.Current.Windows[0];
            //vm.Message = "Fin de la publicación.";
            vm2.start();
            ds.ShowDialog();
        }
    }// end class

    public class RowHeaders : IPGridRowHeader
    {
        public string TopHeaderName { get; set; }
        public List<string> SubHeaders { get; set; }

        public RowHeaders(string topHeaderName, List<string> subHeaders)
        {
            this.TopHeaderName = topHeaderName;
            this.SubHeaders = subHeaders;
        }
    }

    public static class DataGridUtils
    {
        public static DataGridCell GetCell(DataGrid dataGrid, int row, int column)
        {
            DataGridRow rowContainer = GetRow(dataGrid, row);
            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = WPFUtils.GetVisualChild<DataGridCellsPresenter>(rowContainer);
                // try to get the cell but it may possibly be virtualized
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                if (cell == null)
                {
                    // now try to bring into view and retreive the cell
                    dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                }
                return cell;
            }
            return null;
        }

        public static DataGridRow GetRow(DataGrid dataGrid, int index)
        {
            DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
            if (row == null)
            {
                // may be virtualized, bring into view and try again
                dataGrid.ScrollIntoView(dataGrid.Items[index]);
                row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
            }
            return row;
        }
    }//

    public class WPFUtils
    {
        /// <summary>
        /// Gets whether the command assigned to an ICommandSource can execute.
        /// </summary>
        /// <param name="commandSource">The command to verify</param>
        /// <returns><c>true</c> if the command can execute, otherwise false</returns>
        public static bool CanExecuteCommandSource(ICommandSource commandSource)
        {
            ICommand baseCommand = commandSource.Command;
            if (baseCommand == null)
            {
                return false;
            }
            object commandParameter = commandSource.CommandParameter;
            IInputElement commandTarget = commandSource.CommandTarget;
            RoutedCommand command = baseCommand as RoutedCommand;
            if (command == null)
            {
                return baseCommand.CanExecute(commandParameter);
            }
            else if (commandTarget == null)
            {
                commandTarget = commandSource as IInputElement;
            }
            return command.CanExecute(commandParameter, commandTarget);
        }

        /// <summary>
        /// Navigates the visual tree upwards from an to it's parent of the given type.
        /// </summary>
        /// <param name="dependencyObject">The element whose parent to find.</param>
        /// <param name="ancestorType">The type of the parent to find.</param>
        /// <returns>The parent element of the specified type, or null if there is no parent.</returns>
        public static DependencyObject GetParentOfType(DependencyObject dependencyObject, Type ancestorType)
        {
            if (dependencyObject == null)
            {
                return null;
            }
            else if (dependencyObject.GetType() == ancestorType)
            {
                return dependencyObject;
            }
            else
            {
                return GetParentOfType(VisualTreeHelper.GetParent(dependencyObject), ancestorType);
            }
        }

        public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(v);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }

        /// <summary>
        /// Generates a Table which can be added to a FlowDocument.
        /// </summary>
        /// <param name="items">The items to add to the table. Each KeyValuePair is one row</param>
        /// <returns>A Table containing the specified items as rows</returns>
        public static Table GenerateFlowTable(ICollection<KeyValuePair<string, string>> items)
        {
            Table tbl = new Table();
            tbl.Columns.Add(new TableColumn());
            tbl.Columns.Add(new TableColumn());
            tbl.CellSpacing = 0;
            if (items.Count > 0)
            {
                TableRowGroup rows = new TableRowGroup();
                tbl.RowGroups.Add(rows);
                foreach (KeyValuePair<string, string> itemRow in items)
                {
                    TableRow row = new TableRow();
                    TableCell leftCell = new TableCell(new Paragraph(new Run(itemRow.Key))),
                              rightCell = new TableCell(new Paragraph(new Run(itemRow.Value)));
                    row.Cells.Add(leftCell);
                    row.Cells.Add(rightCell);
                    rows.Rows.Add(row);
                }
                rows.Rows[0].FontWeight = FontWeights.Bold;
                rows.Rows[0].Cells[0].TextAlignment = TextAlignment.Center;
                rows.Rows[0].Cells[1].TextAlignment = TextAlignment.Center;
            }
            return tbl;
        }
    }

}
